package com.framework.foundation.weixin.wxdevice;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.framework.foundation.common.BaseService;
import com.framework.foundation.common.vo.BTResult;
import com.framework.foundation.common.vo.IResult;
import com.framework.foundation.common.vo.Result;
import com.framework.foundation.util.ApiConfigUtils;
import com.framework.foundation.weixin.api.WifiApi;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.ApiResult;

public class WxdeviceService extends BaseService<Wxdevice> {

	public static final Log LOG = Log.getLog(WxdeviceService.class);

	public static final WxdeviceService me = Enhancer.enhance(WxdeviceService.class);

	/**
	 * 新增方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	@Before(Tx.class)
	public IResult<Object> save(Wxdevice model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			// 没有密码时设置默认值
			if (StringUtils.isEmpty(model.getStr("password"))) {
				model.set("password", "WX123456");
			}
			// 设置微信配置
			ApiConfigUtils.setApiConfig(model.getInt("wxuser_id"));
			// 微信创建设备
			ApiResult apiResult = WifiApi.addDevice(model);
			if (apiResult.isSucceed()) {
				// 新增时默认当前值即为门店真实值
				model.set("real_ssid", model.get("ssid"));
				model.save();
			}

			return Result.create(apiResult.isSucceed(), apiResult.getStr("errmsg"));
		} catch (Exception e) {
			throw new RuntimeException("新增异常！", e);
		}
	}

	/**
	 * 编辑方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	@Before(Tx.class)
	public IResult<Object> update(Wxdevice model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			Wxdevice device = Wxdevice.me.findById(model.get("id"));
			ApiConfigUtils.setApiConfig(model.getInt("wxuser_id"));
			// 微信api修改设备信息
			ApiResult apiResult = WifiApi.updateDevice(device, model);
			if (apiResult.isSucceed()) {
				// 重新设置当前门店ssid真实值,并改为启用状态
				model.set("real_ssid", model.get("ssid"));
				model.set("enabled", 1);
				model.update();
			}

			return Result.create(apiResult.isSucceed(), apiResult.getStr("errmsg"));
		} catch (Exception e) {
			throw new RuntimeException("编辑异常！", e);
		}
	}

	public IResult<Object> state(Map<String, Object> param) {
		int type = MapUtils.getInteger(param, "type");
		String[] ids = MapUtils.getString(param, "ids").split(",");
		Wxdevice oldDevice = new Wxdevice();
		Wxdevice newDevice = new Wxdevice();
		boolean success = false;
		if ((type == 1) || (type == 2)) {
			for (String id : ids) {
				oldDevice = Wxdevice.me.findById(id);
				newDevice = Wxdevice.me.findById(id);
				boolean flag = false;
				if ((type == 1) && !oldDevice.getBoolean("enabled")) {
					flag = true;
					// 启用,将真实值还原
					newDevice.set("ssid", newDevice.get("real_ssid"));
					newDevice.set("enabled", 1);
				} else if ((type == 2) && oldDevice.getBoolean("enabled")) {
					flag = true;
					// 禁用,随机生成ssid进行修改
					newDevice.set("ssid", "WX-" + newDevice.getInt("shop_id") + "-" + newDevice.getInt("id"));
					newDevice.set("enabled", 0);
				}
				if (flag) {
					// 微信wifi接口进行修改
					ApiConfigUtils.setApiConfig(newDevice.getInt("wxuser_id"));
					ApiResult apiResult = WifiApi.updateDevice(oldDevice, newDevice);
					if (apiResult.isSucceed()) {
						// 只要有一个修改成功则返回成功
						success = true;
						newDevice.update();
					}
				}
			}
		}
		return Result.create(success);
	}

	@Override
	public BTResult<Record> paginate(Map<String, Object> param) {
		String select = "SELECT d.*, (SELECT count(m.id) FROM ww_mac m WHERE m.device_id = d.id) AS mac_count";
		StringBuffer from = new StringBuffer("FROM ww_device d WHERE d.store_id = ? ");
		if (param.get("sortName") != null) {
			from.append(" ORDER BY d." + param.get("sortName") + " " + param.get("sortOrder"));
		}

		Page<Record> pages = Db.paginate(MapUtils.getInteger(param, "pageNumber"),
				MapUtils.getInteger(param, "pageSize"), select, from.toString(), param.get("store_id"));
		return new BTResult<Record>(pages.getTotalRow(), pages.getList());
	}

	@Override
	/**
	 * 物理删除模型
	 * 
	 * @param id数组
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	public IResult<Object> delete(String[] ids) {
		try {
			if (ArrayUtils.isEmpty(ids)) {
				return Result.createFail();
			}
			// 微信删除
			for (String id : ids) {
				Wxdevice device = Wxdevice.me.findById(Integer.parseInt(id));
				ApiConfigUtils.setApiConfig(device.getInt("wxuser_id"));
				ApiResult result = WifiApi.deleteDevice(device);
				if (result.isSucceed()) {
					// 删除设备
					Db.update("DELETE FROM ww_mac WHERE device_id = ?", device.getInt("id"));
					// 删除网络
					device.delete();
				} else {
					return Result.createFail(result.getStr("errmsg"));
				}
			}
			return Result.createSuccess();

		} catch (Exception e) {
			throw new RuntimeException("删除异常---->" + getClass().getSuperclass().getSimpleName(), e);
		}
	}

	/**
	 * 获取物料二维码
	 * 
	 * @Author: Brin
	 * @Date: 2016年3月16日 下午1:31:23
	 */
	public String getQrcode(Map<String, Object> param) {
		int deviceId = MapUtils.getInteger(param, "deviceId");
		int imgId = MapUtils.getInteger(param, "imgId");
		Wxdevice device = Wxdevice.me.findById(deviceId);
		if (device != null) {
			ApiConfigUtils.setApiConfig(device.getInt("wxuser_id"));
			ApiResult apiResult = WifiApi.getWifiQrcode(device.getInt("shop_id"), device.getStr("ssid"), imgId);
			if (apiResult.isSucceed()) {
				Map map = apiResult.getMap("data");
				return map.get("qrcode_url").toString();
			}
		}
		return null;
	}
}
